package utils

import (
	"MoSkeleton/framework/core/consts"
	"encoding/hex"
	"github.com/tjfoc/gmsm/sm4"
	"go.uber.org/zap"
	"path/filepath"
)

var (
	//用于传输的sm4 key
	Trans_Sm4Key sm4.SM4Key
	// 用于存储的sm4 key
	Store_Sm4Key sm4.SM4Key
)

func Sm4Encrypt(key sm4.SM4Key, plainText string) (string, error) {
	sm4Buf, err := sm4.Sm4Cbc(key, []byte(plainText), true)
	if err != nil {
		return "", err
	}
	return hex.EncodeToString(sm4Buf), nil
}

func Sm4Decrypt(key sm4.SM4Key, cipherText string) (string, error) {
	sm4Buf, err := hex.DecodeString(cipherText)
	if err != nil {
		return "", err
	}
	textData, err := sm4.Sm4Cbc(key, sm4Buf, false)
	if err != nil {
		return "", err
	}
	return string(textData), nil
}
func initSm4() {
	var err error
	iv, _ := hex.DecodeString(consts.Sm4_IV)
	err = sm4.SetIV(iv)
	if err != nil {
		MoLogger.Error("sm4 iv init fail", zap.Error(err))
		return
	}
	sm4PemFilename := filepath.Join(WorkDir, consts.PemPath, consts.Sm4_Trans_Pem_File)
	Trans_Sm4Key, err = sm4.ReadKeyFromPemFile(sm4PemFilename, nil)
	if err != nil {
		MoLogger.Error("sm4 key init fail", zap.Error(err))
		return
	}
	sm4PemFilename = filepath.Join(WorkDir, consts.PemPath, consts.Sm4_Store_Pem_File)
	Store_Sm4Key, err = sm4.ReadKeyFromPemFile(sm4PemFilename, nil)
	if err != nil {
		MoLogger.Error("sm4 key init fail", zap.Error(err))
		return
	}
}
func init() {
	initSm4()
}
